package src

import (
	"bytes"
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/gofiber/fiber/v2"
)

type Metric struct {
	Instance string `json:"instance"`
	Job      string `json:"job"`
}

type EvalMatche struct {
	Metric Metric                 `json:"metric"`
	Tags   map[string]interface{} `json:"tags"`
	Value  float64                `json:"value"`
}

type Hook struct {
	DashboardId float64                  `json:"dashboardId"`
	EvalMatches []map[string]interface{} `json:"evalMatches"`
	ImageUrl    string                   `json:"imageUrl"`
	Message     string                   `json:"message"`
	OrgId       float64                  `json:"orgId"`
	PanelId     float64                  `json:"panelId"`
	RuleId      float64                  `json:"ruleId"`
	RuleName    string                   `json:"ruleName"`
	RuleUrl     string                   `json:"ruleUrl"`
	State       string                   `json:"state"`
	Tags        map[string]interface{}   `json:"tags"`
	Title       string                   `json:"title"`
}

func SendImageMsg(c *fiber.Ctx) error {
	h := new(Hook)
	if err := c.BodyParser(h); err != nil {
		fmt.Println(err)
		c.SendString("Error on JSON format")
		return errors.New("error on JSON format")
	}

	botKey := c.Params("key")
	botID, exists := botsKey[botKey]
	if !exists {
		c.SendString("bot key is error")
		return errors.New("bot key is error")
	}
	msgStr := fmt.Sprintf(`
		{
			"msgtype": "news",
			"news": {
			  "articles": [
				{
				  "title": "%s",
				  "description": "%s",
				  "url": "%s",
				  "picurl": "%s"
				}
			  ]
			}
		  }
		`, h.Title, h.Message, h.RuleUrl, h.ImageUrl)

	url := URL + botID
	jsonStr := []byte(msgStr)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	if err != nil {
		c.SendString(err.Error())
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{
		Timeout: 3 * time.Second,
	}
	resp, err := client.Do(req)
	if err != nil {
		c.SendString("Error sending to WeChat Work API")
		return errors.New("error sending to WeChat Work API")
	}
	defer resp.Body.Close()
	c.SendStream(resp.Body)
	return nil
}

// MsgNews 发送消息类型 news
func MsgNews(h *Hook) string {
	return fmt.Sprintf(`
        {
            "msgtype": "news",
            "news": {
              "articles": [
                {
                  "title": "%s",
                  "description": "%s",
                  "url": "%s",
                  "picurl": "%s"
                }
              ]
            }
          }
        `, h.Title, h.Message, h.RuleUrl, h.ImageUrl)
}

// MsgMarkdown 发送消息类型
func MsgMarkdown(h *Hook, color string) string {
	return fmt.Sprintf(`
    {
       "msgtype": "markdown",
       "markdown": {
           "content": "<font color=\"%s\">%s</font>\r\n<font color=\"comment\">%s\r\n[点击查看详情](%s)![](%s)</font>"
       }
  }`, color, h.Title, h.Message, h.RuleUrl, h.ImageUrl)
}
